<?php
/**
 * Created by PhpStorm.
 * User: xding
 * Date: 15/10/19
 * Time: 下午1:41
 */

class Users_model extends CI_Model {

    public static $_TB_NAME = 'users';

    private $conditions;

    // 默认查询起止位置
    private $start = 0;
    private $rows  = 0;

    public function __construct() {
        parent::__construct();
        $this->load->database();
    }


    /**
     * 设置查询条件
     *
     * @param $conditions       查询条件集合
     * @param null $tb_name     表名
     * @param bool|FALSE $reset 是否重置
     * @return $this
     */
    public function set_query_condition($conditions,$tb_name = NULL,$reset = FALSE) {

        // default use user table
        $tb_name =  $tb_name  ?: \Beans\User::$_TB_NAME ;
        // reset conditions
        $reset && $this->conditions = array();

        if ( count($conditions) )
        {
            foreach ( $conditions as $key => $val )
            {
                $key_ = $tb_name . '.' . $key;
                $val_ = $val;

                $this->conditions[$key_] = $val_;
            }
        }

        return $this;
    }

    /**
     * CI在每一次查询结束后回重置查询构造器，此处是将缓存的查询条件再次加入到查询构造器
     * 可以使用CI的查询缓存功能，但是会将缓存的条件同步到其他的Model中得查询构造器中
     */
    private function _set_query_condition() {
        if ( count($this->conditions) )
        {
            foreach ( $this->conditions as $key => $val )
            {
                $this->db->where($key,$val);
            }
        }
    }


    /**
     * @param $start
     * @param $rows
     * @return $this
     * @throws Exception
     */
    public function limit( $start ,$rows ) {

        if ( !is_numeric($start) || !is_numeric($rows) )
            throw new Exception('fetal error: Error params type');

        $this->start = $start;
        $this->rows  = $rows;
        return $this;

    }

    /**
     * 获取表中所有用户的数量
     *
     * @return mixed
     */
    public function get_user_count() {
        $this->_set_query_condition();
        return $this->db->count_all_results( \Beans\User::$_TB_NAME );
    }


    /**
     * 获取用户列表
     *
     * @return null
     */
    public function get_user_list() {

        $this->db->select('*');
        $this->db->from( \Beans\User::$_TB_NAME );
        $this->db->order_by( \Beans\User::$_TB_NAME . '.user_createtime','DESC' );

        // 记录数不为0，则设置limit
        if ( $this->rows != 0 )
        {
            $this->db->limit($this->start,$this->rows);
        }

        $query = $this->db->get();
        if ( !$query->num_rows() )
        {
            return NULL;
        }

        return $query->result();
    }

}